package com.example.realm;

import com.example.po.SysUser;
import com.example.service.SysUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

@Service
public class SysJWTAuthorizingRealm extends AuthorizingRealm {

    @Resource
    private SysUserService sysUserService;

    /****
     *
     * 用户的授权方法
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }


    /****
     *
     * 用户的登陆认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String userName = (String) authenticationToken.getPrincipal();
        if (StringUtils.isEmpty(userName)) {
            throw new AuthenticationException("用户名不可为空");
        }
        SysUser sysUser = this.sysUserService.getUserByLoginName(userName);
        if (sysUser == null) {
            throw new AuthenticationException("未找到用户名: " + userName + " 对应的用户.");
        }
        String passwordInput = new String((char[]) authenticationToken.getCredentials());
        if (!new Sha256Hash(passwordInput).toHex().equals(sysUser.getPassWord())) {
            throw new AuthenticationException("密码错误");
        }
        return new SimpleAuthenticationInfo(sysUser,
                passwordInput, null, getName());
    }
}
